<?php
namespace Admin\Controller;
use Common\Util\AttachmentUtil;
use Services\Upload\OssFileService;
use Think\Controller;

/**
 * 七牛上传
 * @package Home\Controller
 */
class NewUploadController extends BaseController {
    //上传用户
    public $upname = null;
    //上传用户ID
    public $admin_id = 0;
    public $user_id = 0;
    //会员组
    public $groupid = 0;
    //是否后台
    public $isadmin = 0;
    //上传模块
    public $module = 'cms';
    private $uploadUrl = '';
    private $uploadPath = '';
    //编辑器初始配置
    private $confing = array(
        /* 上传图片配置项 */
        "imageActionName" => "uploadimage", /* 执行上传图片的action名称 */
        "imageFieldName" => "upfile", /* 提交的图片表单名称 */
        "imageMaxSize" => 2048000, /* 上传大小限制，单位B */
        "imageAllowFiles" => [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
        "imageCompressEnable" => true, /* 是否压缩图片,默认是true */
        "imageCompressBorder" => 1600, /* 图片压缩最长边限制 */
        "imageInsertAlign" => "none", /* 插入的图片浮动方式 */
        "imageUrlPrefix" => "", /* 图片访问路径前缀 */
        'imagePathFormat' => '',
        /* 涂鸦图片上传配置项 */
        "scrawlActionName" => "uploadscrawl", /* 执行上传涂鸦的action名称 */
        "scrawlFieldName" => "upfile", /* 提交的图片表单名称 */
        'scrawlPathFormat' => '',
        "scrawlMaxSize" => 2048000, /* 上传大小限制，单位B */
        'scrawlUrlPrefix' => '',
        'scrawlInsertAlign' => 'none',
        /* 截图工具上传 */
        "snapscreenActionName" => "uploadimage", /* 执行上传截图的action名称 */
        'snapscreenPathFormat' => '',
        'snapscreenUrlPrefix' => '',
        'snapscreenInsertAlign' => 'none',
        /* 抓取远程图片配置 */
        'catcherLocalDomain' => array('127.0.0.1', 'localhost', 'img.baidu.com'),
        "catcherActionName" => "catchimage", /* 执行抓取远程图片的action名称 */
        'catcherFieldName' => 'source',
        'catcherPathFormat' => '',
        'catcherUrlPrefix' => '',
        'catcherMaxSize' => 0,
        'catcherAllowFiles' => array('.png', '.jpg', '.jpeg', '.gif', '.bmp'),
        /* 上传视频配置 */
        "videoActionName" => "uploadvideo", /* 执行上传视频的action名称 */
        "videoFieldName" => "upfile", /* 提交的视频表单名称 */
        'videoPathFormat' => '',
        'videoUrlPrefix' => '',
        'videoMaxSize' => 0,
        'videoAllowFiles' => array(".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"),
        /* 上传文件配置 */
        "fileActionName" => "uploadfile", /* controller里,执行上传视频的action名称 */
        'fileFieldName' => 'upfile',
        'filePathFormat' => '',
        'fileUrlPrefix' => '',
        'fileMaxSize' => 0,
        'fileAllowFiles' => array(".flv", ".swf"),
        /* 列出指定目录下的图片 */
        "imageManagerActionName" => "listimage", /* 执行图片管理的action名称 */
        'imageManagerListPath' => '',
        'imageManagerListSize' => 20,
        'imageManagerUrlPrefix' => '',
        'imageManagerInsertAlign' => 'none',
        'imageManagerAllowFiles' => array('.png', '.jpg', '.jpeg', '.gif', '.bmp'),
        /* 列出指定目录下的文件 */
        "fileManagerActionName" => "listfile", /* 执行文件管理的action名称 */
        'fileManagerListPath' => '',
        'fileManagerUrlPrefix' => '',
        'fileManagerListSize' => '',
        'fileManagerAllowFiles' => array(".flv", ".swf"),
    );
    /**
     * 上传图片
     */
    public function upload() {
        $action = $_GET['action']?$_GET['action']:'';
        switch ($action) {
            /* 获取配置信息 */
            case 'config':
                $result = $this->confing;
                break;
            /* 上传图片 */
            case 'uploadimage':
                return $this->saveFile();
                break;
            /* 上传涂鸦 */
            case 'uploadscrawl':
                return $this->saveFile('images', 'ueditor_scrawl');
                break;
            /* 上传视频 */
            case 'uploadvideo':
                return $this->saveFile('videos', 'ueditor');
                break;
            /* 上传附件 */
            case 'uploadfile':
                return $this->saveFile('files', 'ueditor');
                break;
            /* 列出图片 */
            case 'listimage':
                return $this->showFileList('listimage');
                break;

            /* 列出附件 */
            case 'listfile':
                return $this->showFileList('listfile');
                break;
            default:
                $result = array(
                    'state' => '请求地址出错',
                );
                break;
        }
        /* 输出结果 */
        if (isset($_GET["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
            } else {
                echo json_encode(['state' => 'callback参数不合法']);
            }
        } else {
            echo json_encode($result);exit();
        }
    }

    protected function saveFile($type='',$style='')
    {
        if (!function_exists("finfo_open")) {
            echo json_encode([
                'code' => -1,
                'info' => '检测到环境未开启php_fileinfo拓展',
                'state' => '检测到环境未开启php_fileinfo拓展', //兼容百度
            ]);exit();
        }
        // 附件大小限制
        $size_limit = 2 * 1024 * 1024;
        // 附件类型限制
        $ext_limit = '';
        // 水印参数
        $watermark = '';
        // 获取附件数据
        $file_input_name = 'upfile';
        $file = $_FILES[$file_input_name];
        if ($file == null) {
            echo json_encode([
                'code' => -1,
                'info' => '获取不到文件信息',
                'state' => '获取不到文件信息', //兼容百度
                'message' => '获取不到文件信息', //兼容editormd
            ]);exit();
        }
        // 判断附件是否已存在
        $file_md5 = get_file_hash($_FILES['upfile']['tmp_name'],'md5');
        $ossFileService = new OssFileService();
		if($file = $ossFileService->getFileByMd5($file_md5)){
            $this->returnSuccess($file,[
                'state' => "SUCCESS",
                'url' => arr_get($file,'url'),
            ]);
        }
        // 判断附件大小是否超过限制

        // 判断附件格式是否符合

        // 附件上传钩子，用于第三方文件上传扩展
        // 实例化上传类

        $driver = C( 'PICTURE_UPLOAD_DRIVER' );
		if($type=='videos'){
			$config = array(
				'maxSize' => 0 , // 2M 上传的文件大小限制 (0-不做限制)
				'exts' => array( 'mp4') , // 允许上传的文件后缀
				'rootPath' => './Uploads/Picture/'
			);
		}else{
			$config = array(
				'maxSize' => 2097152 , // 2M 上传的文件大小限制 (0-不做限制)
				'exts' => array( 'jpg' , 'gif' , 'png' , 'jpeg' ) , // 允许上传的文件后缀
				'rootPath' => './Uploads/Picture/',
                'savePath' => 'admin/'
			);
		}
        $upload = new \Think\Upload( $config , C( 'PICTURE_UPLOAD_DRIVER' ) , get_oss_config());
        // 上传文件
        $info = $upload->uploadOne( $_FILES['upfile']);
        // 上传错误提示错误信息
        if( !$info ){
            $this->returnError($upload->getError());
        }
        $fileInfo = [
            'user_id' => 0,
            'name' => $_FILES['upfile']['name'],
            'mime' => $info['type'],
            'path' => get_url_path($info['url']),
            'suffix' => pathinfo($info['url'])['extension'],
            'ext' => $info['ext'],
            'size' => $info['size'],
            'md5' => $info['md5'],
            'sha1' => $info['sha1'],
            'module' => 'admin',
            'driver'=>'qiniu',
            'created_at'=>date('Y-m-d H:i:s'),
            'updated_at'=>date('Y-m-d H:i:s'),
        ];
        $ossFileService->setParams($fileInfo);
        if ($file = $ossFileService->add()) {
            $this->returnSuccess($file,[
                'state' => "SUCCESS",
                'url' => arr_get($file,'url'),
            ]);
        } else {
            $this->returnError('上传失败');
        }
    }

    protected function showFileList($type = '')
    {
        $filelist = AttachmentUtil::getAccachmentList();
        $i = 0;
        $list = [];
        foreach ($filelist as $value) {
            $list[$i]['id'] = $value['id'];
            $list[$i]['url'] = $value['url'];
            $list[$i]['name'] = $value['name'];
            $list[$i]['size'] = format_bytes($value['size']);
            $list[$i]['mtime'] = $value['create_time'];
            $i++;
        }
        /* 返回数据 */
        $result = array(
            "state" => "SUCCESS",
            "list" => $list,
            "start" => 0,
            "total" => 100,
        );
        echo json_encode($result);exit();
    }
}
